package org.qydjk.common.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 默认30天
 */
public class CookieUtil {
	private static final Log log = LogFactory.getLog(CookieUtil.class);

	//单位为秒，下面为1个月
	private static final int age = 30*24*60*60;

	
	public static void addCookie(HttpServletResponse response, String name, String value){
		addCookie(response, name, value, age,null);
	}

	public static void addCookie(HttpServletResponse response, String name, String value, int age){
		addCookie(response, name, value, age,null);
	}

	public static void addCookie(HttpServletResponse response, String name, String value, String domain){
		addCookie(response, name, value, age,domain);
	}

	public static void addCookie(HttpServletResponse response, String name, String value, int age, String domain){
		Cookie cookies = new Cookie(name, value);
		if(domain != null && !domain.equals("")){
			cookies.setDomain(domain);
		}
		cookies.setPath("/");
		cookies.setMaxAge(age);
		response.addCookie(cookies);
	}

	public static String getCooklieValue(HttpServletRequest request, String name){
		if(name != null && !name.equals("")){
			Cookie cookie = getCookie(request, name);
			if(cookie != null){
				return cookie.getValue();
			}
		}
		return "";
	}
	
	private static Cookie getCookie(HttpServletRequest request, String name){
		Cookie[] cookies = request.getCookies();
		if(cookies == null || cookies.length <= 0){
			return null;
		}
		for (Cookie cookie : cookies) {
			if(cookie.getName().equals(name)){
				return cookie;
			}
		}
		return null;
	}

	/**
	 * 删除cookie
	 * @param request
	 * @param response
	 * @param cookieName
	 * @return
	 */
	public static boolean deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
		if (cookieName != null) {
			Cookie cookie = getCookie(request,cookieName);
			if(cookie!=null){
				cookie.setMaxAge(0);//如果0，就说明立即删除
				cookie.setPath("/");//不要漏掉
				cookie.setValue(null);
				response.addCookie(cookie);
				return true;
			}
		}
		return false;
	}
}
